from Editor import *
import regex
wordregex=regex.compile('.*[^A-Za-z0-9_]\([A-Za-z_][A-Za-z_0-9]*\)$')

_keywords={}
def IndentForLine(text,pos):
	prefix=GetText(LineStart(pos),pos)
	prefix=regsub.sub('[^ \t]+', '',prefix)
	text=regsub.gsub('\n', '\n'+prefix,text)
	return text
 
def SetKeywords(lang,items):
	_keywords[lang]=items
 
def GetKeywords(pat,pos,end):
	stripnl=GetText(end,end+1)=='\n'
	r=regex.compile(pat)
	list=[]
	if _keywords.has_key(GetFileType()):
		for kwd in _keywords[GetFileType()]:
			if r.search(kwd)==0:
				if stripnl and kwd[-1]=='\n':
					kwd=kwd[:-1]
				kwd=IndentForLine(kwd,pos)
				list.append(kwd)
	list.reverse()
	return list

def _Reset():
	global _lastPos, _lastWord, _lastSelected, _todo, _lastSeen
	_lastPos=-1
	_lastWord=''
	_lastSelected=''
	_todo=[]
	_lastSeen=[]
	
_Reset() # get initial values for global variables

def _GetWord(start):
	t=GetText(LineStart(start),start)
	if wordregex.match(' '+t)<0:
		return None
	return wordregex.group(1)

def _GetTodoList(pat,start_pos,end_pos):
	list=[]
	start=0
	reversed=0
	while 1:
		ms,me= Search(pat,start,1) 
		if ms<0:
			break
		if start_pos<=ms<=end_pos:
			start=end_pos+1
			continue # dont get our self
		t=GetText(ms,me)
		if ms>=start_pos and not reversed:
			reversed=1
			list.reverse() # first the closest items

		list.append(t)
		start=ms+1
	if reversed:
		list.reverse()
#	print list
	return list

def WordExpand(case_sensitive=1):
	global _lastWord, _lastPos,_lastSelected,_todo
	(start,end)=GetSelection()
	word=_GetWord(start)
	sel=GetSelectionText()
	if word is None:
		Bell()
		return
	if start!=_lastPos or word!=_lastWord or sel!=_lastSelected:
		_Reset()
		pat='\\<'+word+'[A-Za-z_0-9]+'
		_todo=_GetTodoList(pat,start-len(word),end)+GetKeywords(word,start,end)
	if not _todo:
		InsertText('')
		Bell()
		_Reset()
		return
	while _todo:
		t=_todo[-1]
		del _todo[-1]
		repl=t[len(word):]
		if not t in _lastSeen:
			_lastSeen.append(t)
			break
	InsertText(repl)
	SetSelection(start,start+len(repl))
	_lastSelected=repl
	_lastWord=word
	_lastPos=start



#############################################################################
import string,regsub
def explen(s):
	return len(string.expandtabs(s,GetTabWidth()))
def Slashify(exp='\\'):
	start,end=GetSelection()
	start=LineStart(start)
	txt=GetText(start,end)
	if txt[-1:]!='\n':
		txt=GetText(start,LineEnd(end))
	if txt[-1:]!='\n':
		txt=txt+'\n'
	nt=regsub.gsub("[\t \\]*\n","\n",txt)
	lines=string.splitfields(nt,'\n')[:-1]
	ml=max(map(explen,lines))
	ntxt=''
	nlines=[]
	if exp:
		for l in lines:
			nlines.append(l+(ml-explen(l))*' '+' '+exp)
	else:
		nlines=lines
	repl=string.join(nlines,'\n')
	SetSelection(start,LineEnd(end))
	InsertText(repl)
	SetSelection(start,start+len(repl))
